<template>
    <el-container>
        <el-header>
            <h3>商户信息</h3>
            <el-button @click="logout" round class="logout-button">退出登录</el-button>
        </el-header>

        <el-tabs v-model="activeTab">
            <el-tab-pane label="商户信息" name="merchant-info">
                <el-card v-if="merchant" class="merchant-card">
                    <el-form :model="merchant" ref="merchantForm" label-width="80px" class="horizontal-form">
                        <el-row>
                            <el-col :span="5">
                                <el-form-item label="商户名称" prop="merchant_name">
                                    <el-input v-model="merchant.merchant_name" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="地址" prop="address">
                                    <el-input v-model="merchant.address" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="密码" prop="password">
                                    <el-input v-model="merchant.password" type="password" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" class="button-col">
                                <el-form-item>
                                    <el-button type="primary" @click="updateMerchant">更新</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>
                <el-card v-else class="loading-card">
                    <p>加载商户信息中...</p>
                </el-card>
                <MenuManager />
            </el-tab-pane>

            <el-tab-pane label="订单管理" name="order-management">
                <el-table :data="orders" class="order-table">
                    <el-table-column prop="order_ID" label="订单ID" width="180"></el-table-column>
                    <el-table-column prop="order_status" label="订单状态" width="180">
                        <template #default="scope">
                            <el-tag :type="scope.row.order_status === 0 ? 'warning' : 'success'">
                                {{ scope.row.order_status === 0 ? '已下单' : '已完成' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                        <template #default="scope">
                            <el-button v-if="scope.row.order_status === 0" type="primary" @click="completeOrder(scope.row.order_ID)">
                                完成
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane label="忠实粉丝消费分布" name="consumption-distribution">
                <ConsumptionDistribution />
            </el-tab-pane>
        </el-tabs>
    </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import router from '@/router';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import axios from '@/axios';
import { ElMessage } from 'element-plus';
import MenuManager from '../components/Menu.vue';
import ConsumptionDistribution from '../components/ConsumptionDistribution.vue';

const merchant = ref(null);
const merchantForm = ref(null);
const orders = ref([]);
const activeTab = ref('merchant-info');
const route = useRoute(); 
const store = useStore();

/* 获取商户基本信息 */
const fetchMerchant = async () => {
    try {
        const merchantId = store.state.merchant.id;
        const response = await axios.get(`/api/merchant/getMerchantInfo/${merchantId}`);
        merchant.value = response.data;
    } catch (error) {
        ElMessage.error('获取商户数据出错: ' + error.message);
    }
};

/* 获取订单数据 */
const fetchOrders = async () => {
    try {
        const merchantId = store.state.merchant.id;
        const response = await axios.get(`/api/merchant/getOrders/${merchantId}`);
        orders.value = response.data;
    } catch (error) {
        ElMessage.error('获取订单数据出错: ' + error.message);
    }
};

/* 修改商户信息 */
const updateMerchant = async () => {
    // 检查商户信息不能为空
    if (!merchant.value.merchant_name || !merchant.value.password) {
        ElMessage.warning('商户名称和密码不能为空!');
        return;
    }

    try {
        await axios.put(`/api/merchant/updateMerchantInfo/${merchant.value.merchant_ID}`, {
            merchant_name: merchant.value.merchant_name,
            address: merchant.value.address,
            password: merchant.value.password,
        });
        ElMessage.success('商户信息更新成功!');
    } catch (error) {
        ElMessage.error('更新商户数据出错: ' + error.message);
    }
};

const completeOrder = async (orderId) => {
    try {
        await axios.put(`/api/merchant/updateOrderStatus`, { order_ID: orderId, order_status: 1 });
        orders.value = orders.value.map(order =>   // 更新订单状态，将订单状态改为已完成
            order.order_ID === orderId ? { ...order, order_status: 1 } : order
        );
        ElMessage.success('订单已完成!');
    } catch (error) {
        ElMessage.error('更新订单状态出错: ' + error.message);
    }
};

onMounted(() => {
    fetchMerchant();
    fetchOrders();
});

/* 退出登录 */
const logout = () => {
    store.dispatch('logout', 'merchant');  // 调用 Vuex 的 logout action 清除商户信息
    router.push('/');  // 重定向到登录页面
};

</script>

<style scoped>
.loading-card {
    max-width: 500px;
    margin: 20px auto;
    padding: 20px;
    text-align: center;
}

.el-header {
    background-color: #4e77b9;
    color: white;
    font-size: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.logout-button {
    position: absolute;
    right: 20px;
}

.order-table {
    width: 100%;
    margin-top: 20px;
}
</style>
